/* Created by web-design Ver 1.0.9 */
/**
 * 获取数据集列表接口查询参数
 * @param type 数据集的类型
 * @param programId programId
 * @returns 查询语句
 */
export const getMetaDatas = (type, programId) => {
    return `{ getMetaDatas(sourceType: ${type}, programId: ${programId}) {
        code
        success
        message
        result {
            metaId
            metaName
        }
    }}`
}
/**
 * 获取查询参数语句
 * @param type 数据集的类型
 * @param id 数据集id
 * @returns 查询语句
 */
export const getDataParams = (type, id) => {
    return `{ getMetaDataParams(sourceType: ${type}, metaId: "${id}") {
        code
        success
        message
        result {
            paramName
            paramValue
        }
    }}`
}
/**
 * 获取查询字段语句
 * @param type 数据集的类型
 * @param id 数据集id
 * @returns 查询语句
 */
export const getDataFields = (type, id) => {
    return `{ getMetaDataFields(sourceType: ${type}, metaId: "${id}") {
        code
        success
        message
        result {
            fieldName
            fieldDesc
            fieldValueType
        }
    }}`
}
/**
 * 获取查询数据语句
 * @param type 数据集的类型
 * @param id 数据集id
 * @returns 查询语句
 */
export const getDatas = (type, id, params, pageObj) => {
    let dataParams = 'null'
    let pageParams = ''
    const page = pageObj || { pageNo: 1, pageSize: 10 }
    if (typeof params === 'object') {
        if (params) {
            dataParams = ''
            Object.keys(params).forEach((key) => {
                dataParams += `{ paramName: "${key}", paramValue: "${params[key] || ''}" },`
            })
            dataParams = '[' + dataParams.slice(0, dataParams.length - 1) + ']'
        }
    }
    pageParams = `, pageNo: ${page.pageNo}, pageSize: ${page.pageSize}`
    return `{ getDatas(sourceType: ${type}, id: "${id}", dataParam: ${dataParams}${pageParams}) {
        success
        message
        code
        total
        result
    }}`
}

/**
 * 解析数据
 */
export const formatRemoteData = (data, responseKey) => {
    let resultData = data
    if (responseKey) {
        const bra = responseKey.split('.')
        resultData = bra.reduce((prev, cur) => {
            return prev ? prev[cur] : {}
        }, data)
    }
    return resultData
}

/**
 * 处理数据源请求信息
 * @param response 数据
 */
export const formatResponse = (response, responseKey) => {
    if (response.errors) {
        if (response.errors.length) {
            // 取第一条错误信息
            const firstError = response.errors[0].message
            return new Error(firstError)
        } else {
            return new Error(JSON.stringify(response.errors))
        }
    } else {
        const resultKey = responseKey === 'data.getDatas' ? '' : responseKey
        const responseData = formatRemoteData(response, responseKey)
        if (responseData.success) {
            if (Object.prototype.hasOwnProperty.call(responseData, 'result')) {
                let result = ''
                try {
                    result = JSON.parse(responseData.result)
                } catch (error) {
                    result = responseData.result
                }
                responseData.result = formatRemoteData(result, resultKey)
            }
            return responseData
        } else {
            return new Error(responseData.message)
        }
    }
}
/**
 * 获取URL的query参数
 * @returns {{}}
 */
export const parseUrl = (uri) => {
    let url = uri || window.location.href
    const i = url.indexOf('?')
    const indexHash = url.indexOf('#')
    if (i === -1) return {}
    if (i < indexHash) url = url.slice(0, indexHash)
    const querystr = url.substr(i + 1)
    const arr1 = querystr.split('&')
    const arr2 = {}
    for (const key in arr1) {
        const ta = arr1[key].split('=')
        arr2[ta[0]] = ta[1]
    }
    return arr2
}
/**
 * 格式化时间
 * @param time 时间数据
 * @param fmt  格式化字符串
 * @returns
 */
export const formatDateTime = (time, fmt) => {
    if (time) {
        let curTime = null
        if (time instanceof Date) {
            curTime = time
        } else {
            curTime = new Date(time)
        }
        if (typeof curTime.getTime === 'function' && !isNaN(curTime.getTime())) {
            const o = {
                'M+': curTime.getMonth() + 1,
                'D+': curTime.getDate(),
                'd+': curTime.getDate(),
                'H+': curTime.getHours(),
                'm+': curTime.getMinutes(),
                's+': curTime.getSeconds(),
                'q+': Math.floor((curTime.getMonth() + 3) / 3), // 季度
                S: curTime.getMilliseconds()
            }
            if (/(y|Y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (curTime.getFullYear() + '').substr(4 - RegExp.$1.length))
            }
            for (const k in o) {
                if (new RegExp('(' + k + ')').test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
                }
            }
            return fmt
        }
    }
    return time
}
/**
 * 找到列表对应的数据
 * @param list 列表
 * @param value 值
 * @param valueKey 获取值的字段
 * @param nameKey 获取展示的字段
 * @param emptyText 空值显示的内容
 * @returns
 */
export const formatDict = (list, value, valueKey = 'value', nameKey = 'name', emptyText = '-') => {
    if (value || value === 0) {
        const obj = list.find(item => String(item[valueKey]) === String(value))
        return obj ? obj[nameKey] : emptyText
    } else {
        return emptyText
    }
}

/**
 * 首字母小写
 * @param camelCase 驼峰值
 * @returns 转后的字符串
 */
export const firstLowerCase = (name) => {
	return name.slice(0, 1).toLowerCase() + name.slice(1)
}

/**
 * 下划线转驼峰
 * @param name
 * @returns
 */
export const camelCase = (name) => {
	if (name) {
		const SPECIAL_CHARS_REGEXP = /([:\-_]+(.))/g
		const MOZ_HACK_REGEXP = /^moz([A-Z])/
		return name.replace(SPECIAL_CHARS_REGEXP, function (_, separator, letter, offset) {
			return offset ? letter.toUpperCase() : letter
		}).replace(MOZ_HACK_REGEXP, 'Moz$1').replace(/^\w/, (p1) => p1.toUpperCase())
	} else {
		return name
	}
}
